from django.shortcuts import render,HttpResponse,redirect
from django import views
from .models import *
#生成加密用户ID
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from Login import settings
from itsdangerous import SignatureExpired
#导包
from celery_tasks .tasks import send_active_email
from django.core.mail import send_mail
from django.contrib.auth import authenticate
from django.core.cache import cache
from django.shortcuts import render_to_response
from . import send_sms
from django.http import JsonResponse
from .forms import RegisterForm
import json
# 验证码需要导入的模块
from captcha.models import CaptchaStore
from captcha.helpers import captcha_image_url


# Create your views here.
#注册页面
class Regist(views.View):
    def get(self,request):
        return render(request,'register.html')

    def post(self,request):
        #获取用户输入信息
        name = request.POST.get('user_name')
        password = request.POST.get('pwd')
        email = request.POST.get('email')
        code = request.POST.get('auth_code')
        phone = request.POST.get('phone')
        ok_code = cache.get(phone)
        #去数据库查找用户所输信息是否存在
        x = UserPro.objects.filter(username=name)
        y = UserPro.objects.filter(email=email)
        if x:
            return render(request,'register.html',{'error_msg':'用户名已存在'})
        elif y:
            return render(request,'register.html',{'error_msg':'该邮箱已被使用'})
        elif code != ok_code:
            return render(request,'register.html',{'error_msg':'验证码不正确'})
        elif name == '' or password == '' or email == '':
            return render(request,'register.html',{'error_msg':'信息不完整'})
        else:
            UserPro.objects.create_user(username=name, password=password, email=email, is_active=False)
            users = UserPro.objects.filter(username=name)
            #加密用户id，生成有效时间为1小时的验证链接
            serializer = Serializer(settings.SECRET_KEY,3600)
            for i in users:
                user = i
                info = {'confirm': user.id}
                token = serializer.dumps(info).decode(encoding='utf-8')
                send_active_email.delay(email, name, token)
                # subject = '日圆生鲜欢迎你'  #邮件标题
                # message = 'how are you'   #邮件正文
                # sender = settings.EMAIL_FROM   #发件人
                # receiver = [email]   #收件人
                # html_message = """
                # <h1>%s  恭喜您成为日圆生鲜注册会员</h1><br/><h3>请您在1小时内点击以下链接进行账户激 活，领取漂亮女朋友</h3><a href="http://127.0.0.1:8000/user/active/%s">http://127.0.0.1:8000/user/active/%s</a>
                # """ %(user.username, token, token)
                # # 调用自带的发邮件方法
                # send_mail(subject,message,sender,receiver,html_message=html_message)
                # print(token)
                return redirect('index')

#登陆界面
class Login(views.View):
    def get(self,request):
        if 'username' in request.COOKIES:
            username = request.COOKIES.get('username')
            checked = 'checked'
        else:
            username = ''
            checked = ''
        register_form = RegisterForm()
        print(username)
        return render(request,'login.html',{'username':username,"checked":checked,'register_form':register_form})

    def post(self,request):
        name = request.POST.get('username')
        password = request.POST.get('pwd')
        remeber = request.POST.get('remeber')
        code = request.POST.get('code')
        hashkey = request.POST.get('hashkey')
        cs = CaptchaStore.objects.filter(response=str(code),hashkey=hashkey)

        register_form = RegisterForm(request.POST)

        #验证用户名密码是否匹配
        a = authenticate(username=name,password=password)
        if a is not None:
            if a.is_active == 1:
                if remeber == 'on':
                    request.session['username'] = name
                    request.set_cookie('username',name,max_age=7*24*3600)
                else:
                    request.delete_cookie('username')
                user_name = request.session.get('username')
                return render(request, 'index.html', {'name':user_name})
            else:
                return render(request,'login.html',{'error_msg': '该用户未激活'})
        elif cs is None:
            return render(request,'login.html',{'error_msg': '验证码错误'})
        else:
            return render(request,'login.html',{'error_msg': '用户名或密码不正确'})

class Index(views.View):
    def get(self,request):
        return render(request,'index.html')
    def post(self,request):
        return HttpResponse('ok')


#用户激活
class Activate(views.View):
    def get(self,request,token):
        serializer = Serializer(settings.SECRET_KEY, 3600)
        try:
            info = serializer.loads(token)
            user_id = info['confirm']
            user = UserPro.objects.get(id=user_id)
            user.is_active = 1
            user.save()
            return redirect('login')
        except SignatureExpired as e:
            return HttpResponse('激活链接超时')

#发送短信
def send_post(request):

    phone = str(request.GET.get('phone'))
    code = send_sms.get_code(6,False)
    cache.set(phone, code, 60)  # 60s有效期

    result = send_sms.send_sms(phone, code)
    return HttpResponse(result)


#短信验证码校验
def sms_check(request):
    # /duanxin/sms_check/?phone=xxx&code=xxx    
    #  1. 电话和手动输入的验证
    phone = request.GET.get('phone')
    code = request.GET.get('code')

    # 2.获取redis中保存的code
    # print('缓存中是否包含：',cache.has_key(phone))
    # print('取值：',cache.get(phone))
    ok_code = cache.get(phone)
    # 3.判断
    if code == ok_code:
        return JsonResponse({'code':'验证码正确'})
    else:
        return JsonResponse({'code':'验证码错误'})



#图文验证码刷新
def img_refresh(request):
    if not request.is_ajax():
        return HttpResponse('不是ajax请求')
    new_key = CaptchaStore.generate_key()
    to_json_response = {
        'hashkey':new_key,
        'img_url':captcha_image_url(new_key),
    }

    return HttpResponse(json.dumps(to_json_response))

#验证
def img_check(request):
    print('验证用户输入的图片验证码')
    if request.is_ajax():
        cs = CaptchaStore.objects.filter(response=str(request.GET.get('code')),
                                        hashkey=request.GET.get('hashkey'))

        print(cs)

        if cs:
            json_data = {'status':1}

        else:
            json_data = {'status':0}
        return JsonResponse(json_data)
    else:
        #raiseHttp404
        json_data = {'status':0}
        return JsonResponse(json_data)


#手写图形验证码：
#
# def get_varify(request):
#
#     #定义画布颜色
#     bg_color = get_random_color()
#     #画布大小
#     img_size =(130,70)
#     #定义画布
#     image = Image.new('RGB',img_size,bg_color)
#     #定义画笔
#     draw = ImageDraw.Draw(image,'RGB')
#     #创建字体
#     font_path = 'C:\Windows\Fonts\Arial.ttf'
#     #实例化字体
#     font = ImageFont.truetype(font_path,30)
#     #准备画布上的字符集
#     source = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM0123456789'
#     #保存每次随即出来的字符
#     code_str = ""
#
#     for i in range(4):
#         #获取数字随机颜色
#         text_color = get_random_color()
#         #获取随机数字
#         tmp_num = random.randrange(len(source))
#         #获取随机字符，画布上的字符集
#         random_str = source[tmp_num]
#         #将每次随机到的字符保存，并遍历四次
#         code_str += random_str
#         #将字符画到画布上
#         draw.text((10+30*i,20),random_str,text_color,font)
#     #记录生成的字符到session中
#     request.session['img_code'] = code_str
#
#     #获得一个缓存区
#     buf = io.BytesIO()
#     image.save(buf,'png')
#     return HttpResponse(buf.getvalue(),'img/png')



#判断用户是否登陆
def check_user(request):
    user = request.session.get('username')
    return user

#点击购物车
def cart(request):
    if check_user(request):
        return render(request,'cart.html',{'name':check_user(request)})
    else:
        return redirect('login')

#用户退出
def exit(request):
    del request.session['username']
    a = request.session.get('username')
    print(a)
    return redirect('login')


def page_not_found(request,**kwargs):

    response = render_to_response('404.html',{})

    response.status_code = 404
    return response

def page_error(request,**kwargs):

    response = render_to_response('500.html',{})
    response.status_code = 500
    return response
